package UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    private DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        this.socket = new DatagramSocket(port);
    }
    //启动服务器
    public void start() throws IOException {
        System.out.println("server start!");
        while (true){
            //1、读取请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(requestPacket);
            //receive收到的数据是二进制数据，而我们需要的是字符串，需要进行转换
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            //2、根据请求计算响应
            String response = process(request);
            //3、把响应返回给客户端，
            DatagramPacket responsePacket = new DatagramPacket(
                    response.getBytes(),response.getBytes().length,requestPacket.getSocketAddress());//需要再次构造一个DatagramPacket
            socket.send(responsePacket);
            //4、打印日志
            System.out.printf("[%s : %d],request: %s,response: %s\n",
                    requestPacket.getAddress().toString(),requestPacket.getPort(),request,response);
        }
    }
    public String process(String request){//表示 根据请求 计算 响应 的方法
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(6060);
        server.start();
    }
}
